package com.nlecloud.bc.service.contract.impl;

import com.nlecloud.bc.constant.CustomerConstant;
import com.nlecloud.bc.contract.User;
import com.nlecloud.bc.service.contract.IUserContractService;
import lombok.extern.slf4j.Slf4j;
import org.fisco.bcos.sdk.client.Client;
import org.fisco.bcos.sdk.model.TransactionReceipt;
import org.fisco.bcos.sdk.transaction.model.exception.ContractException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;

/**
 * @author warrior
 * @description 账户合约操作服务接口实现
 */
@Service
@Slf4j
public class UserContractService implements IUserContractService {

    @Value("${fisco.bcos.contract.user.address}")
    private String contractUserAddress;

    @Autowired
    private Client client;

    @Override
    public boolean setBalance(String userId, String amount) {
        User user = User.load(contractUserAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        TransactionReceipt transactionReceipt = user.setBalance(userId, new BigInteger(amount));
        log.info("set balance traction receipt {}", transactionReceipt.toString());
        String status = transactionReceipt.getStatus();
        return CustomerConstant.SUCCESS_STATUS.equals(status);
    }

    @Override
    public BigInteger getBalance(String userId) throws ContractException {
        User user = User.load(contractUserAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        return user.getBalance(userId);
    }

    @Override
    public boolean transfer(String uuid, String userId) {
        User user = User.load(contractUserAddress, client, client.getCryptoSuite().getCryptoKeyPair());
        TransactionReceipt transactionReceipt = user.transfer(userId,uuid);
        log.info("transfer uuid {} userId {}, traction receipt {}", uuid, userId, transactionReceipt.toString());
        String status = transactionReceipt.getStatus();
        return CustomerConstant.SUCCESS_STATUS.equals(status);
    }
}
